﻿using UnityEngine;

namespace Game
{
    public class SceneObjectHpBarComponent : ISceneComponent
    {
        private SceneBattleEntity _battleEntity;
        private SceneSharedPropertiesComponent _sceneSharedPropertiesComponent;
        private SceneObjectBattlePropertiesComponent _propertiesComponent;
        private SceneHpBarEntity _hpBar;
        
        public SceneObjectHpBarComponent()
        {
            _hpBar = new SceneHpBarEntity();
            _hpBar.LoadHpBar();
            _hpBar.SetParent(GameUISystem.Instance.canvas.transform);
        }
        
        public void Dispose()
        {
            _hpBar.Dispose();
            _hpBar = null;
        }

        public void Setup(SceneBattleEntity battleEntity)
        {
            _battleEntity = battleEntity;
            _sceneSharedPropertiesComponent = _battleEntity.GetComponent<SceneSharedPropertiesComponent>();
            _propertiesComponent = _battleEntity.GetComponent<SceneObjectBattlePropertiesComponent>();
            UpdateHpPercent();
        }

        public void Update(float deltaTime)
        {
            UpdateHpPercent();
            Vector2 screenPoint = _sceneSharedPropertiesComponent.camera.WorldToScreenPoint(_battleEntity.position +
                new Vector3(0f, _battleEntity.bounds.size.y, 0f));
            RectTransform parentTransform = GameUISystem.Instance.canvasTransform;
            Vector3 worldPoint;
            if (RectTransformUtility.ScreenPointToWorldPointInRectangle(parentTransform, screenPoint,
                GameUISystem.Instance.camera,
                out worldPoint))
            {
                _hpBar.position = worldPoint;
            }
        }

        private void UpdateHpPercent()
        {
            _hpBar.SetHpPercent(1.0f * _propertiesComponent.GetProperty(SceneObjectBattlePropertyKeys.Hp) / 
                                _propertiesComponent.GetProperty(SceneObjectBattlePropertyKeys.MaxHp));
        }
    }
}